package com.wang.aspect;

import com.wang.common.Log;
import com.wang.exception.BusinessException;
import com.wang.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class LogAspect {

    @Pointcut("@annotation(com.wang.common.Log)")
    public void aop() {

    }

    @Around("aop()")
    public Object aroundAdvice(ProceedingJoinPoint pjp) {
        Object result = null;
        BusinessException bx = null;
        Throwable exception = null;
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Log annotation = signature.getMethod().getAnnotation(Log.class);
        String serviceName = annotation.serviceName();
        Object obj = pjp.getArgs()[0];
        log.info("******请求接口：【{}】，请求参数：【{}】", serviceName, Utils.logJson(obj));
        try {
            result = pjp.proceed();
        } catch (BusinessException businessException) {
            bx = businessException;
            log.error(bx.getMessage(), bx);
        } catch (Throwable throwable) {
            exception = throwable;
            log.error(throwable.getMessage(), throwable);
        }
        if (bx != null || exception != null) {
            return null;
        }
        log.info("******响应接口：【{}】，响应参数：【{}】", serviceName, Utils.logJson(result));
        return result;
    }
}
